<template>
    <div class="container">
        <!-- {{year}}-{{month}}-{{day}} -->
        <div class="calendar">
            <div class="date_label">日期：</div>
            <div class="date_status">
                <!-- 月份 -->
                <div class="data_months">
                    <span v-for="(item, index) in monthArr" :key="index"
                        :class="{'redWarning':warningMonths.includes(item),'active':Number(month) == item}"
                        :data-value="item" @click="monthClick">{{
                        item }}月</span>
                </div>
                <!-- 天数 -->
                <div class="date_days">
                    <span v-for="(item, index) in dayArr" :key="index"
                        :class="{'redWarning': warningDays.includes(item),'active':Number(day) == item}"
                        :data-value="item" @click="dayClick">{{ item
                        }}日
                    </span>
                </div>
            </div>

        </div>
    </div>
</template>

<script>
import { onMounted, ref, reactive, toRefs, computed, watch } from 'vue';
export default {
    props: {
        warningDate:{
            type: Object,
            default: () => ({})
        }
    },
    setup(props, context) {
        const { emit }=context;
        console.log('props:==========', props)
        // 预警日期，接口获得
        const { warningDate } = toRefs(props)
        // const warningDate = ref({
        //     '01': ['01', '03', '06'],
        //     '03': ['02', '05', '08', '10'],
        //     '05': ['08', '10', '12', '16'],
        //     '10': ['05', '08', '11', '14'],
        // })

        // 预警月份
        const warningMonths = computed(() => {
            return Object.keys(warningDate.value).map(item => Number(item).toString())
        })

        const showFlag = computed(() => {
            return Object.keys(warningDate.value).length > 0
        })

        // 当前月份，预警天数
        const warningDays = reactive([])

        // 获取月份的预警天数
        watch(() => warningDate.value, () => {
            getWarningDays(state.month)
        },{deep:true})
        const getWarningDays = (currMonth) => {
            let date = new Date();
            let month = addZero(date.getMonth() + 1);
            const activeMonth = currMonth || month
            warningDays.length = 0 // 清空
            warningDate['value'][activeMonth] ? warningDate['value'][activeMonth].forEach(item => {
                warningDays.push(Number(item).toString())
            }) : null; // 注意不能直接赋值，会改变引用
        }

        const state = reactive({
            year: '', // 年
            month: '', // 月
            day: '', // 日
            monthArr: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], // 月份数组
            dayArr: [], // 当前月份的天数
        });

        const addZero = (date) => {
            // 月、日个位数 补零
            return date.toString().padStart(2, '0');
        };

        const setDateArr = (newDate) => {
            // 获得当前月份的所有天数
            let date = new Date(newDate);
            state.year = date.getFullYear().toString();
            state.month = addZero(date.getMonth() + 1); // 补零
            state.day = addZero(date.getDate()); // 补零

            // let firstDay = new Date(state.year, state.month - 1, 1).getDay(); // 每月第一天星期几

            let monthNum = new Date(state.year, state.month, -1).getDate() + 1; // 每月天数

            for (let i = 1; i < monthNum + 1; i++) {
                state.dayArr.push(i.toString()); // 遍历添加当前月份的每一天
            }
            // for (let i = 0; i < firstDay; i++) {
            //     state.dayArr.unshift(''); // 根据第一天在数组前填充字符串，确定第一天是星期几
            // }
        };

        //根据月份获取天数
        const getDaysInMonth = (month, year) => {
            const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
            if (month == '02' || month == 2) {
                year = parseInt(year);
                daysInMonth[1] = (((0 == year % 4) && (0 != (year % 100))) ||
                    (0 == year % 400)) ? 29 : 28;
            }
            let flag = month.substr(0, 1);
            if (flag == 0) {
                month = month.substr(1, 1);
            }
            return daysInMonth[month - 1];
        }

        const monthClick = (event) => {
            console.log('月份：', event.currentTarget.getAttribute('data-value'));
            // 切换选中月份和选中月份对应的预警天数
            let currMonth = event.currentTarget.getAttribute('data-value');
            state.month = addZero(currMonth)
            getWarningDays(addZero(currMonth))

            // 切换选中月份对应的天数
            let monthNum = getDaysInMonth(state.month,state.year)
            state.dayArr.length = 0
            for (let i = 1; i < monthNum + 1; i++) {
                state.dayArr.push(i.toString()); // 遍历添加当前月份的每一天
            }

            // 若选中月份的天数小于切换之前选中的天数
            monthNum < state.day ? state.day = monthNum : null

            // 将日期传给父组件
            emit('changeDate', {'year':state.year,'month':state.month,'day':state.day})
        }
        const dayClick = (event) => {
            console.log('天数：', event.currentTarget.getAttribute('data-value'));
            // 切换选中天数
            let currDay = event.currentTarget.getAttribute('data-value');
            state.day = addZero(currDay)

            // 将日期传给父组件
            emit('changeDate', {'year':state.year,'month':state.month,'day':state.day})
        }

        onMounted(() => {
            // 初始化日期组件
            setDateArr(new Date());
            // 获取默认月份的预警天数
            getWarningDays()
        });

        return {
            ...toRefs(state), // 将 state 返回出去，就可以直接使用 state 里面的属性
            showFlag,
            warningMonths,
            warningDays,
            monthClick,
            dayClick
        };
    },
};
</script>

<style scoped lang="less">
.container {
    .calendar {
        display: flex;
        align-items: center;

        .date_label {
            width: 26px;
        }

        .date_status span {
            display: inline-block;
            word-break: keep-all;
            width: 26px;
            height: 20px;
            margin: 4px;
            font-size: 12px;
            text-align: center;
            cursor: pointer;
        }
    }
}

.active {
    background-color: #bce4f5;
    color: #fff;
}

.redWarning {
    color: #09d43d;
}
</style>
